import java.util.ArrayList;


public class BinarySearch {
    public static void main(String[] args) {
        //int arr[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
        //System.out.println(binarySearch(arr, 0, arr.length - 1, 0));
        int arr[] = {1, 1, 1, 1, 1, 1, 1, 1};
        ArrayList<Integer> list = binarySearch2(arr, 0, arr.length - 1, 2);
        System.out.println(list);
    }

    public static int binarySearch(int[] arr, int left, int right, int value) {
        //如果左指针大于右指针时说明整个数组都没找到对应的值
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        if (value < arr[mid]) {
            return binarySearch(arr, left, mid - 1, value);
        } else if (value > arr[mid]) {
            return binarySearch(arr, mid + 1, right, value);
        } else {
            return mid;
        }
    }

    //如果需要查找出所有=value的值的下标
    public static ArrayList<Integer> binarySearch2(int[] arr, int left, int right, int value) {
        //如果左指针大于右指针时说明整个数组都没找到对应的值
        if (left > right) {
            return new ArrayList<Integer>();
        }
        int mid = (left + right) / 2;
        if (value < arr[mid]) {
            return binarySearch2(arr, left, mid - 1, value);
        } else if (value > arr[mid]) {
            return binarySearch2(arr, mid + 1, right, value);
        } else {
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = mid - 1; i >= 0 && arr[i] == arr[mid]; i--) {
                list.add(i);
            }
            list.add(mid);
            for (int i = mid + 1; i <= arr.length - 1 && arr[i] == arr[mid]; i++) {
                list.add(i);
            }
            return list;
        }
    }
}
